﻿using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
using RestSharp;
using Spotted.Data.Args;
using Spotted.Data.Entities;

namespace Spotted.Data.Repositories.Impl
{
    public class RestBingPlacesRepository : IPlacesRepository
    {
        private const string BingPlacesApiKey = "AmTrxrAzCLeFmrLeUisuQb8uMJh989MnYv-U3mAdofZ7g1kCj20ZmKS1qMgCy8MB";
        private IList<Place> _placesList;
 
        public RestBingPlacesRepository()
        {
            _placesList = new List<Place>();
        }

        #region Implementation of IPlacesRepository

        /// <summary>
        /// A list of the places found near the given point
        /// </summary>
        public IList<Place> Places
        {
            get { return _placesList; }
        }

        /// <summary>
        /// Given Latitude and Longitude values find nearby places
        /// </summary>
        /// <param name="latitude">The current latitude</param>
        /// <param name="longitude">The current longitude</param>
        public void FindNearbyPlaces(double latitude, double longitude)
        {
            var client = new RestClient("http://dev.virtualearth.net/REST/v1");
            var request = new RestRequest(string.Format("/Locations/{0},{1}", latitude, longitude), Method.GET);
            request.AddParameter("key", BingPlacesApiKey);
            request.AddParameter("o", "json");

            client.ExecuteAsync(request, (response, handler) =>
                                             {
                                                 JObject jsonObject = JObject.Parse(response.Content);
                                                 JArray jsonArray = JArray.Parse(jsonObject["resourceSets"][0]["resources"].ToString());

                                                 _placesList = (from location in jsonArray
                                                                select new Place
                                                                           {
                                                                               Name = location["name"].ToString()
                                                                           }).ToList();

                                                 if (FindNearbyPlacesCompleted != null)
                                                     FindNearbyPlacesCompleted(this, new EventArgs());
                                             });
        }

        public event EventHandler FindNearbyPlacesCompleted;

        #endregion
    }
}
